const cloud = require('wx-server-sdk');
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const formatTime = (date, index) => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()
  if(index == 0) {
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute].map(formatNumber).join(':')
  } else if(index == 1) {
    return [year, month, day].map(formatNumber).join('') + [hour, minute].map(formatNumber).join('')
  }
}
//这里最好也初始化一下你的云开发环境
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
//操作excel用的类库
const xlsx = require('node-xlsx');

// 云函数入口函数
exports.main = async(event, context) => {
  try {
    //1,定义excel表格名
    var now = new Date(Date.now() + (8 * 60 * 60 * 1000));
    var number = now.getSeconds() % 43; //这将产生一个基于目前时间的0到42的整数
    var time = formatTime(now, 1)
    let dataCVS = 'excel/' + time + '_' + number + '.xlsx'
    // //2，定义存储数据的
    let alldata = []
    let row = ['出入口名称', '出入类型', '出入时间', '姓名', '性别', '年龄', '身份证号', '联系电话', '体温', '是否咳嗽', '其他症状', '车牌号', '出发地', '目的地', '补充说明']; //表属性
    alldata.push(row);

    let datas = event.datas
    for (let i in datas) {
      let arr = []
      arr.push(datas[i].address[0].address_name)
      arr.push(datas[i].type == "1" ? "出" : "入")
      arr.push(formatTime(new Date(datas[i].time), 0))
      arr.push(datas[i].name)
      arr.push(datas[i].sex == "1" ? "男" : "女")
      arr.push(datas[i].age)
      arr.push(datas[i].id_card)
      arr.push(datas[i].tel)
      arr.push(datas[i].temperature)
      arr.push(datas[i].is_cough == "1" ? "是" : "否")
      arr.push(datas[i].other_symptoms.join("、"))
      arr.push(datas[i].car_id)
      arr.push(datas[i].origin)
      arr.push(datas[i].destination)
      arr.push(datas[i].info_added)
      alldata.push(arr)
    }
    // 把数据保存到excel里
    var buffer = await xlsx.build([{
      name: "mySheetName",
      data: alldata
    }]);
    // 把excel文件保存到云存储里
    return await cloud.uploadFile({
      cloudPath: dataCVS,
      fileContent: buffer, //excel二进制文件
    })
  } catch (e) {
    return {
      d: e
    }
  }
}